package com.weiyuwqj.server.service.account.service.impl;

import com.github.pagehelper.PageHelper;
import com.weiyuwqj.api.common.PageList;
import com.weiyuwqj.api.common.Paginator;
import com.weiyuwqj.api.constant.Global;
import com.weiyuwqj.api.constant.Message;
import com.weiyuwqj.api.exception.CrowdException;
import com.weiyuwqj.api.exception.HfException;
//import com.weiyuwqj.api.hengfeng.PayConstants;
//import com.weiyuwqj.api.hengfeng.model.base.HfBaseResponseBean;
//import com.weiyuwqj.api.hengfeng.model.base.HfResultBean;
//import com.weiyuwqj.api.hengfeng.model.platform.HfPlatformWithdraw;
//import com.weiyuwqj.api.hengfeng.model.recharge.HfQuickRechargeRequestByShop;
import com.weiyuwqj.api.model.BasUser;
import com.weiyuwqj.api.model.BasUserInfo;
import com.weiyuwqj.api.model.BusAccount;
import com.weiyuwqj.api.model.BusAccountBank;
import com.weiyuwqj.api.model.BusAccountCash;
import com.weiyuwqj.api.model.SysFee;
import com.weiyuwqj.api.model.vo.BusAccountCashVo;
import com.weiyuwqj.api.service.BusAccountCashService;
import com.weiyuwqj.api.util.DateUtils;
import com.weiyuwqj.api.util.IpUtils;
import com.weiyuwqj.api.util.ParamUtils;
import com.weiyuwqj.api.util.StringUtils;
import com.weiyuwqj.server.mapper.BasUserInfoMapper;
import com.weiyuwqj.server.mapper.BasUserMapper;
import com.weiyuwqj.server.mapper.BusAccountBankMapper;
import com.weiyuwqj.server.mapper.BusAccountCashMapper;
import com.weiyuwqj.server.mapper.BusAccountMapper;
import com.weiyuwqj.server.mapper.BusUserStatMapper;
import com.weiyuwqj.server.mapper.SysFeeMapper;
//import com.weiyuwqj.server.pay.FundApi;
//import com.weiyuwqj.server.pay.PlatformApi;
import com.weiyuwqj.server.service.account.module.DealAction;
import com.weiyuwqj.server.service.account.module.DealModule;
import com.weiyuwqj.server.service.account.module.action.BackCashDealAction;
import com.weiyuwqj.server.service.account.module.action.CashDealAction;
import com.weiyuwqj.server.service.account.module.action.VerifyCashDealAction;
import com.weiyuwqj.server.service.base.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

@Service("accountCashService")
public class BusAccountCashServiceImpl extends BaseServiceImpl<BusAccountCash> implements BusAccountCashService {

    private static Logger log = Logger.getLogger("accountCashService");

    @Autowired
    private BusAccountCashMapper busAccountCashMapper;

    @Autowired
    private DealModule dealModule;

    @Autowired
    private BasUserMapper userMapper;

    @Autowired
    private BusUserStatMapper userStatMapper;

    @Autowired
    private BusAccountBankMapper accountBankMapper;

    @Autowired
    private BasUserInfoMapper userInfoMapper;

    @Autowired
    private BusAccountMapper accountMapper;

    @Autowired
    private SysFeeMapper sysFeeMapper;



//    @Autowired
//    private FundApi fundApi;
//
//    @Autowired
//    private PlatformApi platformApi;

    @Override
    public void updateBusAccountCashStatus(String orderNo, int oldStatus,
                                           int newStatus, String addIp) {
        int i = busAccountCashMapper.updateAccountCashStatus(orderNo, oldStatus, newStatus);
        if (i < 1) {
            throw new CrowdException("account.status.change_error");
        }

        BusAccountCash cash = busAccountCashMapper.findBusAccountCashByOrderNo(orderNo);
        cash.setAuditTime(new Date());
        busAccountCashMapper.updateByPrimaryKey(cash);

        sysFeeMapper.updateStatus(newStatus,oldStatus,orderNo);

        int count;
        if (newStatus == 1) {
            //成功
            DealAction action = new VerifyCashDealAction();
            action.deal(cash.getUserId(), cash.getCashAmount(), "用户提现成功");
            count = dealModule.dealAction(action);
            if (count < 1) {
                throw new CrowdException("update_error");
            }

            Map cashMap = new HashMap();
            cashMap.put("userId", cash.getUserId());
            cashMap.put("cashAmount", cash.getActualAmount());
            userStatMapper.updateCash(cashMap);

        } else if (newStatus == 0) {
            //提现驳回
            DealAction action = new BackCashDealAction();
            action.deal(cash.getUserId(), cash.getCashAmount(), "用户提现驳回");
            count = dealModule.dealAction(action);
            if (count < 1) {
                throw new CrowdException("update_error");
            }
        }
    }

    @Override
    public BusAccountCash findBusAccountCashByOrderNo(String orderNo) {
        BusAccountCash busAccountCash = new BusAccountCash();
        busAccountCash = busAccountCashMapper.findBusAccountCashByOrderNo(orderNo);
        if (busAccountCash == null) {
            throw new CrowdException("account.recharge.no_found_error");
        }
        return busAccountCash;
    }

    @Override
    public List<BusAccountCash> findBusAccountCashByStatus(int status) {
        List<BusAccountCash> busAccountCashs = busAccountCashMapper.findBusAccountCashByStatus(status);
        if (busAccountCashs == null) {
            throw new CrowdException("account.recharge.no_found_error");
        }
        return busAccountCashs;
    }

    @Override
    public List<BusAccountCash> findBusAccountCashByUserId(int userId) {
        List<BusAccountCash> busAccountCashs = busAccountCashMapper.findBusAccountCashByUserId(userId);
        if (busAccountCashs == null) {
            throw new CrowdException("account.recharge.no_found_error");
        }
        return busAccountCashs;
    }

    @Override
    public PageList getList(Paginator p, Map<String, Object> param) {
        PageHelper.startPage(p.getPageNum(), p.getPageSize());
        List<BusAccountCashVo> list = busAccountCashMapper.getList(param);
        return new PageList(list);
    }

    @Override
    public BusAccountCashVo getSingle(Map<String, Object> param) {
        return busAccountCashMapper.getSingle(param);
    }

    //获取用户当日提现总金额
    @Override
    public Integer getTodayWithdrawTotal(Integer userId) {
        return busAccountCashMapper.getTodayWithdrawTotal(userId);
    }

    @Override
    public List<BusAccountCashVo> excelList(Map<String, Object> param) {
        return busAccountCashMapper.getList(param);
    }


    @Override
    public Integer getMonthlyWithdrawTotal(Map map) {
        return busAccountCashMapper.getMonthlyWithdrawTotal(map);
    }

    //后台首页提现金额统计
    @Override
    public Map countCashAmount() {
        return busAccountCashMapper.countCashAmount();
    }

    @Override
    public BigDecimal sumCashAmountByUserId(Integer userId) {
        return busAccountCashMapper.sumCashAmountByUserId(userId);
    }

    @Override
    public PageList getListByUserId(Paginator p, Integer userId) {
        PageHelper.startPage(p.getPageNum(), p.getPageSize());
        List<BusAccountCashVo> list = busAccountCashMapper.getListByUserId(userId);
        return new PageList(list);
    }

    @Override
    public PageList getDailyList(Paginator p, Map<String, Object> map) {
        PageHelper.startPage(p.getPageNum(), p.getPageSize());
        List<BusAccountCashVo> list = busAccountCashMapper.getDailyList(map);
        return new PageList(list);
    }

    @Override
    public List<Map> statCashAmount(Map map) {
        return busAccountCashMapper.statCashAmount(map);
    }

    @Override
    public List<BusAccountCashVo> getList(Map map) {
        return busAccountCashMapper.getList(map);
    }


    //提现
    @Override
    public BusAccountCash doCash(BigDecimal amount, Integer userId, String resource) {

        //判断最低可提现金额
        if (amount.compareTo(new BigDecimal(100)) == -1) {
            throw new CrowdException("cash_amount.less");
        }

        //判断可提金额
        String orderNo = StringUtils.getOrderNo();
        BusAccount account = accountMapper.getBusAccountByUserId(userId);
        if (-1 == account.getCash().compareTo(amount)) {
            throw new CrowdException("user.cash.amount.balance_is_not_enough");
        }

        //判断用户是否提现限制
        BasUserInfo info = userInfoMapper.getOneByUserId(userId);
        if (info == null || info.getCashLimit() == 1) {
            throw new CrowdException("cash.sys_limit");
        }

        //判断银行卡
        Map param = new HashMap();
        param.put("status", 1);
        param.put("userId", userId);
        BusAccountBank bank = accountBankMapper.getOneByUserIdAndStatus(param);
        if (null == bank) {
            throw new CrowdException("user.cash.bank.no_already_certified");
        }

        //判断是否到达提现额度
        Date beginDate = DateUtils.getDayStartTime(new Date());
        Date endDate = DateUtils.getNextDayStartTime(new Date());
        BigDecimal userCashAmount = busAccountCashMapper.sumCashAmountByDateAndUserId(beginDate, endDate, userId);//用户之前未失败的提现金额
        if((userCashAmount.add(amount)).compareTo(new BigDecimal(Global.getUserWithdrawAmount())) == 1){
            throw new CrowdException("user.cash.quota.balance_is_not_enough");
        }
        BigDecimal platformCashAmount = busAccountCashMapper.sumCashAmountByDateAndUserId(beginDate, endDate,null);//平台之前未失败的提现金额
        if((platformCashAmount.add(amount)).compareTo(new BigDecimal(Global.getPlatformWithdrawAmount())) == 1){
            throw new CrowdException("platform.cash.quota.balance_is_not_enough");
        }

        //插入提现记录
        BusAccountCash accountCash = new BusAccountCash();
        accountCash.setAddip(IpUtils.get());
        accountCash.setAddtime(new Date());
        accountCash.setCardNo(bank.getCardNo());
        accountCash.setOrderNo(orderNo);
        accountCash.setCashAmount(amount);
        accountCash.setFeeAmount(new BigDecimal(1.5));
        accountCash.setActualAmount(amount);
        accountCash.setBankName(bank.getBankName());
        accountCash.setStatus(2);
        accountCash.setType(2);
        accountCash.setSubBranch(bank.getSubBranch());
        accountCash.setUserId(userId);
        busAccountCashMapper.insertCash(accountCash);

        //插入手续费记录
        SysFee sysFee = new SysFee();
        sysFee.setAddip(IpUtils.get());
        sysFee.setAddtime(new Date());
        sysFee.setOrderNo(orderNo);
        sysFee.setDealAmount(amount);
        sysFee.setFeeAmount(new BigDecimal(1.5));
        sysFee.setSource(resource);
        sysFee.setRechargeId(0);
        sysFee.setCashId(accountCash.getId());
        sysFee.setStatus(2);
        sysFee.setType(2);
        sysFee.setUserId(userId);
        sysFeeMapper.insert(sysFee);

        return accountCash;
    }

    //后台提现趋势图
    @Override

    public List<Map> getRegionGroupCountCashList(Map map) {
        return busAccountCashMapper.getRegionGroupCountCashList(map);
    }


//    @Override
//    public void doHfWithdraw(BusAccountCash cash) {
//        //受理成功用户余额转待收
//        DealAction action = new CashDealAction();
//        action.deal(cash.getUserId(), cash.getCashAmount(), "用户提现");
//        int count = dealModule.dealAction(action);
//        if (count < 1) {
//            throw new CrowdException("update_error");
//        }
//
//        //提现成功
//        DealAction successAction = new VerifyCashDealAction();
//        successAction.deal(cash.getUserId(), cash.getCashAmount(), "用户提现成功");
//        count = dealModule.dealAction(successAction);
//        if (count < 1) {
//            throw new CrowdException("update_error");
//        }
//
//        count = busAccountCashMapper.updateAccountCashStatus(cash.getOrderNo(), 2, 1); //成功更新状态
//        if (count < 1) {
//            throw new CrowdException("update_error");
//        }
//
//        //请求恒丰
//        BasUser basUser = userMapper.selectByPrimaryKey(cash.getUserId());
//        HfResultBean result = fundApi.withdraw(cash.getCashAmount().longValue(), basUser, cash.getOrderNo());
//        if (!result.isSuccess()) {
//            //受理失败
//            log.info(cash.getOrderNo() + result.getMessageText());
//            throw new HfException("HfException", result.getMessageText());
//        }
//    }

    @Override
    public int updateRemarkByOrderNo(String orderNo, String remark) {
        return busAccountCashMapper.updateRemarkByOrderNo(orderNo, remark);
    }

//    /**
//     * 平台提现
//     *
//     * @param amount
//     * @param orderNo
//     * @return
//     */
//    @Override
//    public Map platformWithdraw(String amount, String orderNo) {
//        //受理成功用户余额转待收
//        DealAction action = new CashDealAction();
//        action.deal(Integer.parseInt(Global.getOwnChildAccountId()), new BigDecimal(amount), "平台提现");
//        int count = dealModule.dealAction(action);
//        if (count < 1) {
//            throw new CrowdException("update_error");
//        }
//        HfPlatformWithdraw platformWithdraw = new HfPlatformWithdraw();
//        platformWithdraw.setOrder_no(orderNo);
//        platformWithdraw.setNotify_url(Global.getPlatformWithdrawNoticeUrl());
//        platformWithdraw.setAmount(amount);
//        //请求恒丰
//	    HfResultBean result = platformApi.doPlatWithdraw(platformWithdraw);
//	    return Message.OK;
//    }

//	@Override
//	public HfResultBean quickRecharegeByShop(HfQuickRechargeRequestByShop quickRechargeRequestByShop) {
//		return fundApi.quickRecharegeByShop(quickRechargeRequestByShop);
//	}

}
